'''
	aco-netdesign -- Ant colony optimization solution to network design problem

	Copyright (C) 2008 Jeffrey Sharkey, http://jsharkey.org/
	
	Developed by Jeffrey Sharkey as part of his thesis work at Montana State
	University. His work was sponsored by the Western Transportation Institute,
	and was guided by advisor Doug Galarus. Other valuable guidance was
	provided by Dr. Bill Jameson and Gary Schoep. 

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''


# script to gather statistics from aco output file
# >>> dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension


import os
import re
import math

# using sf0 and cm1
names = [
	"output-mar5-cm0-finished",
	"output-mar5-cm1-finished",
	"output-mar5-sf0-finished"
]


def avg(items):
	total = 0
	for value in items:
		total += value.best()
	return total / len(items)

def avggens(items):
	total = 0
	for value in items:
		total += value.converg(0.5)
	return total / len(items)

def stddev(items):
	average = avg(items)
	total = 0
	for value in items:
		total += pow(value.best() - average, 2)
	return math.sqrt(total / len(items))


class Instance:
	def __init__(self):
		self.alpha = 0
		self.generation = []
	
	def best(self):
		best = self.generation[0]
		for value in self.generation:
			if value < best:
				best = value
		return best
	
	def converg(self, diff):
		last = self.generation[0] + diff
		bestgen = 0.0
		gen = 0.0
		for value in self.generation:
			gen += 1.0
			if last - value > diff:
				bestgen = gen
			last = value
		return bestgen

for name in names:

	findappr = re.compile("##...approx.cost.([0-9\\.]+)")
	findgen = re.compile("overallBest.cost=([0-9\\.]+)")
	findsumm = re.compile("##.heur.([0-9\\.]+).+")
	
	overall = []
	instance = Instance()
	
	summary = {}
	
	infile = open(name+".txt")
	for line in infile:
		appr = findappr.search(line)
		if appr:
			approx = float(appr.group(1))
		
		gen = findgen.search(line)
		if gen:
			value = float(gen.group(1))
			instance.generation.append(value)
		
		summ = findsumm.search(line)
		if summ:
			alpha = float(summ.group(1))
			instance.alpha = alpha
			summary[alpha] = []
			overall.append(instance)
			instance = Instance()
	
	
	# now go create statistics and dump for gnuplot
	
	plotfile = open(name+".plot", "w")
	datafile = open(name+".dat", "w")
	
	plotfile.write("\nset terminal png")
	plotfile.write("\nset output '%s.png'" % (name))
	
	plotfile.write("\nset key bottom left")
	plotfile.write("\nset log x")
	plotfile.write("\nset xlabel '\\alpha'")
	plotfile.write("\nset ylabel 'Solution cost ($k)'")
	plotfile.write("\nset y2label 'ACO generations'")
	plotfile.write("\nset xrange [1.5:130]")
	plotfile.write("\nset y2range [0:16]")
	plotfile.write("\nset ytics nomirror")
	plotfile.write("\nset y2tics 0, 4")
	
	
	plotfile.write("\nplot '%s.dat' using 1:2:3 with errorlines title 'ACO cost' axis x1y1, \\" % (name))
	plotfile.write("\n	%f title '2-approximation cost' axis x1y1, \\" % (approx))
	plotfile.write("\n	'' using 1:4 title 'ACO generations' axis x1y2")
	
	
	
	for instance in overall:
		(summary[instance.alpha]).append(instance)
	
	keys = summary.keys()
	for alpha in sorted(keys):
		items = summary[alpha]
		datafile.write("\n%f\t%f\t%f\t%f" % (alpha, avg(items), stddev(items), avggens(items)+1))
		
	
	#summary = sorted(summary.iteritems(), key=lambda (k,v): (v,k))
	#for alpha, items in summary:
	#	print alpha
	#	datafile.write("\n%f\t%f\t%f\t%f" % (alpha, avg(items), stddev(items), avggens(items)))
	
	plotfile.close()
	datafile.close()
	
	
	os.system("gnuplot %s.plot" % (name))
	

